const Request = require( '../apiModules/request' );
const $request = new Request();
const config = require( '../config' );

module.exports = {
    async getAccessToken(code) {
        const data = await $request.doAction( {
            method: 'post',
            actionUrl: config.authUrl + '/auth/oauth/token',
            headers: {
                "Content-Type": "application/x-www-form-urlencoded"
            },
            params: {
                code: code,
                grant_type: 'authorization_code',
                client_id: 'bdh-bi',
                client_secret: 'Dtt123456',
                redirect_uri: `${config.domain}/login`
            }
        } ).then( data => data ).catch( err => err );
        return data;
    },

    async getUserId(accessToken){
        const data = await $request.doAction({
            method: 'get',
            actionUrl: config.gatewayUrl + '/users/currentUser',
            headers:{
                Authorization: `Bearer ${accessToken}`
            }
        }).then(data => data).catch(err => err);
        return data;
    },

    async refreshToken(token) {
        const data = await $request.doAction( {
            method: 'post',
            actionUrl: config.authUrl + '/auth/oauth/token',
            headers: {
                "Content-Type": "application/x-www-form-urlencoded"
            },
            params: {
                grant_type: 'refresh_token',
                refresh_token: token,
                client_id: 'bdh-bi',
                client_secret: 'Dtt123456'
            }
        } ).then( data => data ).catch( err => err );
        return data;
    },

    async logout(accessToken){
        const data = await $request.doAction({
            method: 'get',
            actionUrl: config.authUrl + '/auth/logout',
            headers:{
                Authorization: `Bearer ${accessToken}`
            }
        }).then(data => data).catch(err => err);
        return data;
    },
}
